package com.fingard.dsp.bank.directbank.jscb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import static com.fingard.io.FileHelper.*;
import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @author Green
 */
public class JSCB01BatPayRec extends JSCB01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.reqSeqID = p_req1988.reqBatchNO;

        StringBuilder content = new StringBuilder();
        content.append("ACNO|CUR_CODE|ACNAME|CARDFLAG|AMT|POSTSCRIPT|\n");

        while (p_req1988.readRecord()) {
            //            收款账号|币种|收款账户名称|卡折标志|金额|附言|
            content.append(String.format("%s|%s|%s|%s|%s|%s|\n", p_req1988.readedDetail.recAct, "01", p_req1988.readedDetail.recName, "", p_req1988.readedDetail.payAmount, p_req1988.readedDetail.abstractATS));
        }

        String fileName = p_req1988.reqBatchNO + ".txt";
        String path = trimEndFileSp(bankFront.serverUpload);
        boolean result = bankWriteFile(path, fileName, content);

        if (!result) {
            retAts.writeStart();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("写入文件" + path + "失败，请检查");
            retAts.writeEnd();
            return retAts;
        }

        JSCB01Header bankHeader = new JSCB01Header();
        bankHeader.transCode = "300002";
        bankHeader.reqSeqNo = p_req1988.reqHeader.reqSeqID;
        bankHeader.fileFlag = "1";

        XmlTextWriter xmlWriter = new XmlTextWriter();
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("body");
        xmlWriter.writeElementString("pay_acno", p_req1988.ownAct);
        xmlWriter.writeElementString("pay_cur_code", "01");
        xmlWriter.writeElementString("pay_acname", p_req1988.ownActName);
        xmlWriter.writeElementString("pay_accaddr", "");
        //0：不需要 1：需要 账簿标志
        xmlWriter.writeElementString("as_flag", "0");
        xmlWriter.writeElementString("as_acno", "");
        xmlWriter.writeElementString("as_acname", "");
        xmlWriter.writeElementString("supply_item", "0008");
        xmlWriter.writeElementString("batch_no", p_req1988.reqBatchNO);
        xmlWriter.writeElementString("count", p_req1988.totalNum);
        xmlWriter.writeElementString("amt", p_req1988.totalAmt);
        xmlWriter.writeElementString("purpose", "代发工资");
        xmlWriter.writeElementString("reserved3", "");
        xmlWriter.writeElementString("file_name", fileName);
        xmlWriter.writeElementString("field_num", "6");
        xmlWriter.writeElementString("record_num", p_req1988.totalNum);
        xmlWriter.writeEndDocument();

        String[] retStrArr = sendToBank(xmlWriter.toXmlString());

        if (retStrArr[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);

            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                String tmpSuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                if ("0000".equals(tmpRetCode)) {
                    retAts.respCode = "0";
                    retAts.respInfo = tmpRetInfo;
                    retAts.newReqSeqID = tmpBkReader.getFirstText("/ap/body/host_serial_no");
                    retAts.transState = tmpRetCode+"+"+tmpBkReader.getFirstText("/ap/body/stat");
                    retAts.payInfoCode = "I4001";
                    retAts.writeRetToATS();

                    //记录serial_no
                    StringBuilder serialNo = new StringBuilder(p_req1988.reqBatchNO + "|" + tmpBkReader.getFirstText("/ap/head/serial_no"));
                    String serriName = p_req1988.reqBatchNO + "_serial_no";
                    //交易成功，写入不做判断
                    String serialNoPath = trimEndFileSp(getBankConfig().getValueAsString("Path"));
                    bankWriteFile(serialNoPath, serriName, serialNo);
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetInfo);
                    retAts.writeRetToATS();
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
                retAts.writeRetToATS();
            }
        } else {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(retStrArr[1]);
            retAts.writeRetToATS();
        }

        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;
        RetAtsBatPayRecDetail detail = new RetAtsBatPayRecDetail();
        JSCB01Header bankHeader = new JSCB01Header();
        bankHeader.transCode = "200201";
        bankHeader.reqSeqNo = p_req1998.reqHeader.transSeqID;
        bankHeader.fileFlag = "1";
        //读取
        String path = getBankConfig().getValueAsString("Path");
        path = trimEndFileSp(path) + File.separator + p_req1998.reqBatchNO + "_serial_no";
        String serialNo = readFileText(path, getCharset());
        if (!StringHelper.isNullOrEmpty(serialNo)) {
            serialNo = serialNo.split("\\|")[1];
        } else {
            serialNo = getSerialNumber(p_req1998.bgnDate, p_req1998.reqBatchNO);
        }
        //end
        if (StringHelper.isNullOrEmpty(serialNo)) {
            retAts.writeStart();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("对应流水号为空，请检查");
            retAts.writeEnd();
            return retAts;
        }

        bankHeader.serial_no = serialNo;


        XmlTextWriter xmlWriter = new XmlTextWriter();
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("body");
        xmlWriter.writeElementString("cms_corp_no", bankFront.org);
        Date d = new Date();
        xmlWriter.writeElementString("tr_acdt", Format.Date8Format.format(d));

        xmlWriter.writeElementString("serial_no", serialNo);
        xmlWriter.writeElementString("batch_no", p_req1998.reqBatchNO);

        xmlWriter.writeEndElement();//body
        xmlWriter.writeEndElement();//ap
        xmlWriter.writeEndDocument();

        String[] retStrArr = sendToBank(xmlWriter.toXmlString());

        if (retStrArr[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);

            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                String tmpSuccFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                if ("0000".equals(tmpRetCode)) {
                    retAts.respCode = "0";
                    int count = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/record_num"));
                    /*                    交易序号0|收款账号(C35)1|收款账号币种(C2)2|收款账号户名(C70)3|卡标志位4|金额5|摘要6|交易日期7|交易时间8|状态9|错误信息10|批次号11|*/
                    String fileFlag = tmpBkReader.getFirstText("/ap/head/file_flag");
                    String filename = tmpBkReader.getFirstText("/ap/body/file_name");
                    if (!StringHelper.isNullOrEmpty(filename)) {
                        String receivePath = getBankConfig().getValueAsString("ReceivePath");
                        StringBuilder sbDownLog = new StringBuilder();
                        SmbFileUtil.smbDownload(receivePath, bankFront.serverUpload, filename,sbDownLog);
                        String fullPath = trimEndFileSp(receivePath) + File.separator + filename;
                        if (existFile(fullPath)) {
                            String fileContent = new String();
                            fileContent = readFileText(fullPath, getCharset());
                            int curFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));
                            StringBuilder curSbLog = new StringBuilder();
                            ArrayList<String[]> curDataList = MFSHelper.getTextArray(fileContent, "|", curFieldNum, count + 1, curSbLog);
                            if (curSbLog.length() == 0) {
                                for (int i = 1; i < curDataList.size(); i++) {
                                    detail = new RetAtsBatPayRecDetail();
                                    String[] curRowDataArr = curDataList.get(i);
                                    detail.memo = curRowDataArr[10].trim();
                                    detail.postScript = curRowDataArr[6].trim();
                                    detail.result = curRowDataArr[9].trim();
                                    detail.payInfoCode = curRowDataArr[9].trim();
                                    retAts.writeRetDetail(detail);
                                }
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(fullPath + "对应路径不存在，请检查前置机所在文件夹");
                        }
                    } else if ("0".equals(fileFlag)) {
                        String fileContent = new String();
                        fileContent = tmpBkReader.getFirstText("/ap/body/serial_record");
                        int curFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));
                        StringBuilder curSbLog = new StringBuilder();
                        ArrayList<String[]> curDataList = MFSHelper.getTextArray(fileContent, "|", curFieldNum, count + 1, curSbLog);
                        if (curSbLog.length() == 0) {
                            for (int i = 1; i < curDataList.size(); i++) {
                                detail = new RetAtsBatPayRecDetail();
                                String[] curRowDataArr = curDataList.get(i);
                                detail.memo = curRowDataArr[10].trim();
                                detail.postScript = curRowDataArr[6].trim();
                                detail.result = curRowDataArr[9].trim();
                                detail.payInfoCode = curRowDataArr[10].trim();
                                detail.recAct = curRowDataArr[1].trim();
                                detail.recName = curRowDataArr[3].trim();
                                detail.payAmount = curRowDataArr[5].trim();
                                detail.curType = getBankConfig().getMapKeyByValue("currencyMapping",curRowDataArr[2].trim());
                                retAts.writeRetDetail(detail);
                            }
                        }
                    } else {
                        retAts.respInfo = "银行未返回file_name节点，请检查报文";
                    }
                } else {
                    retAts.writeStart();
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetInfo);
                }
            } else {
                retAts.writeStart();
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
            }
        } else {
            retAts.writeStart();
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(retStrArr[1]);
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

    public Boolean bankWriteFile(String path, String fileName, StringBuilder content) {
        Boolean retBool = false;
        if (StringHelper.isNullOrEmpty(path)) {
            WriteBankLogLn("文件夹位置为空");
            return retBool;
        }

        if (StringHelper.isNullOrEmpty(fileName)) {
            WriteBankLogLn("文件名为空");
            return retBool;
        }

        if (StringHelper.isNullOrEmpty(content.toString())) {
            WriteBankLogLn("文件内容为空");
            return retBool;
        }

        path = trimEndFileSp(path);
        String fullPath = path + File.separator + fileName;
        //共享目录
        if (path.startsWith("smb://")) {
            StringBuilder tmpSbFile = new StringBuilder();
            try {
                int retUpload = SmbFileUtil.smbWrite(fullPath, content.toString(), getCharset(), tmpSbFile);
                if (retUpload < 0) {
                    WriteBankLogLn("写入共享目录出错 ：" + fullPath);
                    return false;
                } else {
                    return true;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                WriteBankLogLn("写入共享目录出错 ：" + fullPath);
                return false;
            }
        }
        //本地
        else if (!existFile(path)) {
            WriteBankLogLn("文件夹" + path + "不存在，创建对应目录");
            mkdir(path);
            WriteBankLogLn(path + "创建成功");
        }


        try {
            WriteBankLogLn("开始写入文件" + fullPath);
            writeFile(fullPath, content.toString(), getCharset());
            WriteBankLogLn("写入完成");
            retBool = true;
        } catch (Exception ex) {
            ex.printStackTrace();
            WriteBankLogLn("写入文件失败");
            retBool = false;
        }
        return retBool;
    }

    public String getSerialNumber(String bgnDate, String reqBatchNo) throws Exception {
        String retStr = "";
        if (StringHelper.isNullOrEmpty(bgnDate)) {
            WriteBankLogLn("输入日期为空");
            return retStr;
        }
        if (StringHelper.isNullOrEmpty(reqBatchNo)) {
            WriteBankLogLn("输入批次号为空");
            return retStr;
        }
        JSCB01Header header = new JSCB01Header();
        header.transCode = "200100";
        XmlTextWriter xmlWriter = new XmlTextWriter();
        writeCommonHeader(xmlWriter, header);
        String bankDate = "";
        try {
            Date d = Format.DateTimeFormat.parse(bgnDate);
            bankDate = Format.Date8Format.format(d);
        } catch (Exception ex) {
            ex.printStackTrace();
            WriteBankLogLn("转换日期出错");
            return retStr;
        }

        xmlWriter.writeStartElement("body");
        xmlWriter.writeElementString("cms_corp_no", "");
        xmlWriter.writeElementString("start_date", bankDate);
        xmlWriter.writeElementString("end_date", bankDate);
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();

        String[] retStrArr = sendToBank(xmlWriter.toXmlString());

        if (retStrArr[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                if ("0000".equals(tmpRetCode)) {
                    //节点返回
                    String[] record = null;
                    if ("0".equals(tmpBkReader.getFirstText("/ap/head/file_flag"))) {
                        String details = tmpBkReader.getFirstText("/ap/body/serial_record");
                        record = details.split("\\|");
                    }
                    //文件返回
                    else {
                        String receivePath = getBankConfig().getValueAsString("ReceivePath");
                        String fileName = tmpBkReader.getFirstText("/ap/head/file_name");
                        StringBuilder smbSb = new StringBuilder();
                        SmbFileUtil.smbDownload(receivePath, bankFront.serverUpload, fileName,smbSb);
                        String details = readFileText(trimEndFileSp(receivePath) + File.separator + fileName, getCharset());
                        record = details.split("\\|");
                    }
                    String countStr = tmpBkReader.getFirstText("/ap/body/field_num");
                    int count = Integer.parseInt(countStr);
                    for (int i = 0; i < record.length; i += count) {
                        if (reqBatchNo.equals(record[i]) && (i - 1) >= 0) {
                            retStr = record[i - 1];
                            break;
                        }
                    }
                } else {
                    WriteBankLogLn("出错原因" + tmpRetInfo);
                }
            } else {
                WriteBankLogLn("出错原因：" + tmpSbMsg.toString());
            }
        } else {
            WriteBankLogLn("出错原因：" + retStrArr[1]);
        }
        return retStr;
    }
}